<?php
class LeavewordModel extends Model{
	private $table1 = 'leaveword';
	private $table2 = 'products';
	private $table3 = 'membership';
	
	/**
	 * 根据会员id获取留言记录
	 * @param $where,$uid
	 */
	public function getLeaveById($where){
		//$sql = "SELECT * FROM ".$this->table1." WHERE to_uid=".$uid." GROUP"
		 $list = M($this->table1)->table($this->table1." l")->join($this->table3." m ON l.uid=m.uid")->where($where)->order('l.leaveword_id asc')->field('l.*,m.name')->select();
		 foreach($list as $key=>$val){
		 	//var_dump($val);die;
		 	$result = M($this->table1)->table($this->table1." l")->join($this->table3." m ON l.uid=m.uid")->where(array('l.reply_leaveword_id'=>$val['leaveword_id']))->order('l.leaveword_id desc')->field('l.*,m.name')->find();
		 	//echo  M($this->table1)->getLastSql();die;
		 	if($result){
		 		$list[$key]['endleave']=$result;		 		
		 	}else{
		 		$list[$key]['endleave']=0;
		 	}		 	
		 	
		 }
		 return $list;
		//echo M($this->table1)->getLastSql();die;
	}
	
	/**
	 * 获取同一个记录的全部留言信息
	 * @param $where
	 */
	public function getAllLeave($where){
		return  M($this->table1)->where($where)->select();
		 //echo M($this->table1)->getLastSql();die;
	}
	
	/**
	 * 查看会员是否有新的留言
	 * @param $uid 会员id
	 */
	public function getNreply($uid){
		$map['l.uid'] = $uid;
		$map['l.to_uid']  = $uid;
		$map['_logic'] = 'or';
		$where['_complex'] = $map;
		$where['l.reply_leaveword_id']=0;
		$leaveword = $this->getLeaveById($where);
		//var_dump($leaveword);die;
		$count = 0;
		foreach($leaveword as $key=>$val){
			if($val['endleave']==0){
				if($val['to_uid'] == $uid)$count++;
			}else{
				if($val['endleave']['to_uid'] ==$uid)$count++;
			}
		}
		return $count;
	}
}